<template>
<div class="member-wrap">
    <van-nav-bar title="会员升级" left-text="返回" right-text="我的卡券" left-arrow @click-left="onClickLeft" @click-right="onClickRight" />
    <div>
        <van-tabs v-model="active" color="white">
            <van-tab title="秒抢卡">
                <van-tabs v-model="c_index" type="card">
                    <van-tab :title="item.title" v-for="(item,index) in cardData" :key="index">
                        <div class="card_image">
                            <img style="width: 100%;hieght:100%;" :src="item.avatar" />
                            <span class="money">
                                {{ item.money | money }}
                                / {{ item.day }}天

                            </span>
                        </div>
                    </van-tab>
                </van-tabs>
            </van-tab>
            <van-tab title="爆品券">
                <van-cell-group v-if="couponsData[0]">
                    <van-cell :title="couponsData[0].price +' 元'">
                        <div slot="right-icon">
                            <van-stepper v-model="value" input-width="40px" button-size="32px" />
                        </div>
                    </van-cell>
                </van-cell-group>
            </van-tab>
            <button class="btn" @click="pay">立即购买</button>

        </van-tabs>
    </div>
    <van-action-sheet v-model="payLayer" :actions="actions" cancel-text="取消" @cancel="onCancel" title="支付方式" @select="onSelect" />
</div>
</template>

<script>
import wx from 'weixin-js-sdk'
import { Dialog } from 'vant';

export default {
    name: "member",
    data() {
        return {
            active: 0,
            c_index: 0,
            value: 1,
            cardData: [],
            couponsData: [],
            actions: [{
                    name: '微信支付',
                    color: '#07c160'
                },
                {
                    name: '余额支付',
                }
            ],
            payLayer: false
        };
    },
    created() {
        if (this.$route.query.type == 'check') {
            this.active = 1
        }
        this.getList()
    },
    methods: {
        getList() {
            let params = [];
            params.token = sessionStorage.getItem("token");
            this.axios.get('/api/store/user/card/list', {
                params
            }).then(res => {
                this.cardData = res.data.data.card;
                this.couponsData = res.data.data.coupons;
            }).catch(err => {
                console.log(err);
            })
        },
        getData() {
            console.log(this);
        },
        onClickLeft() {
            this.$router.go(-1);
        },
        onClickRight() {
            this.$router.push({
                name: 'coupon',
                path: '/coupon'
            })
        },
        onCancel() {
            this.payLayer = false;
        },
        pay() {
            this.payLayer = true;
        },
        onSelect(e) {
            let params = {};
            params.token = sessionStorage.getItem("token");
            let mode = e.name;
            switch (mode) {
                case '微信支付':
                    if (this.active == 0) {
                        params.price = this.cardData[this.c_index].money;
                        params.params = JSON.stringify(this.cardData[this.c_index]);
                        this.axios.post('api/store/user/card/buy/wechat', params).then(res => {
                            this.wxPay(res.data.data);
                        }).catch(err => {
                            console.log(err);
                        })
                    } else {
                        params.price = (this.couponsData[0].price * 100) * this.value / 100;
                        params.params = JSON.stringify(this.couponsData[0]);
                        params.num = this.value;
                        this.axios.post('api/store/user/coupons/buy/wechat', params).then(res => {
                            this.wxPay(res.data.data)
                        }).catch(err => {
                            console.log(err);
                        })
                    }
                    break;
                case '余额支付':
                    if (this.active == 0) {
                        params.price = this.cardData[this.c_index].money;
                        params.params = JSON.stringify(this.cardData[this.c_index]);
                        this.axios.post('api/store/user/card/buy', params).then(res => {
                            this.payLayer = false;
                            Dialog({
                                message: '购买成功'
                            });
                            this.$router.push({
                                name: 'coupon',
                                path: '/coupon'
                            })
                        }).catch(err => {
                            console.log(err);
                        })
                    } else {
                        params.price = (this.couponsData[0].price * 100) * this.value / 100;
                        params.params = JSON.stringify(this.couponsData[0]);
                        params.num = this.value;
                        this.axios.post('api/store/user/coupons/buy', params).then(res => {
                             this.payLayer = false;
                            Dialog({
                                message: '购买成功'
                            });
                            this.$router.push({
                                name: 'coupon',
                                path: '/coupon'
                            })
                        }).catch(err => {
                            console.log(err);
                        })
                    }
                    break;
            }

        },
        wxPay(data) {
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: data.appId, // 必填，公众号的唯一标识
                timestamp: data.timestamp, // 必填，生成签名的时间戳
                nonceStr: data.nonceStr, // 必填，生成签名的随机串
                signature: data.signature, // 必填，签名，见附录1
                jsApiList: ['chooseWXPay'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            });
            wx.ready(function () {
                wx.chooseWXPay({
                    timestamp: data.timestamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
                    nonceStr: data.nonceStr, // 支付签名随机串，不长于 32 位
                    package: data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=***）
                    signType: 'MD5', // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
                    paySign: data.paySign, // 支付签名
                    success: function (res) {
                        // 支付成功后的回调函数
                        if (res.errMsg == "chooseWXPay:ok") {
                            Dialog({
                                message: '支付成功'
                            });
                        } else {
                            Dialog({
                                message: '错误'
                            });
                        }
                    },
                    error: function () {
                        Dialog({
                            message: '支付失败'
                        });
                    },
                    cancel: function () {
                        Dialog({
                            message: '取消支付'
                        });
                    }
                });
            });
        }
    }
};
</script>

<style scoped>
.box {
    width: 94%;
    height: 60px;
    background: #89c997;
    border-radius: 5px;
}

.card_image {
    padding-top: 7px;
    width: 91%;
    margin: 0 auto;
    position: relative;
}

.card_image img {
    border-radius: 4px;
}

.card_image span.money {
    position: absolute;
    bottom: 1rem;
    right: .75rem;
    font-size: 16px;
    color: white;
}

.top {
    color: white;
    text-indent: 10px;
    height: 40px;
    line-height: 30px;
    font-size: 16px;
}

.bottom {
    color: white;
    height: 20px;
    line-height: 20px;
    font-size: 13px;
    padding: 0 10px;
}

.btn {
    width: 100%;
    height: 45px;
    position: fixed;
    bottom: 0;
    background: #46A85C;
    border: none;
    color: white;
    left: 0;
    right: 0
}
</style>
